package cc.rengu.oltp.service.realize.impl;

import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.dao.BinInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.BinInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.BinInfo;
import cc.rengu.oltp.service.realize.BinInfoService;
import cc.rengu.oltp.utility.util.RedisUtil;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;
import com.alibaba.fastjson.JSON;

import java.util.List;

public class BinInfoServiceImpl implements BinInfoService {
    private final RgLogger rglog = RgLog.getLogger(this.getClass().getName());

    @Override
    public BinInfo getCardBinInfo(String cardNo) throws Exception {
        if (null == cardNo || cardNo.trim().isEmpty() || cardNo.trim().length() < 6) {
            rglog.error("卡号<{}>为空或者卡号不合法!", cardNo);
            return null;
        }
        String binInfoKey = AppParamConstant.BIN_CACHE_KEY + cardNo.substring(0, 6);
        List<BinInfo> binInfoList = JSON.parseArray(RedisUtil.hashGet(AppParamConstant.CARD_BIN_CACHE, binInfoKey), BinInfo.class);
        if (null == binInfoList || binInfoList.isEmpty()) {
            binInfoKey = AppParamConstant.BIN_CACHE_KEY;
            binInfoList = JSON.parseArray(RedisUtil.hashGet(AppParamConstant.CARD_BIN_CACHE, binInfoKey), BinInfo.class);
            if (null == binInfoList || binInfoList.isEmpty()) {
                BinInfoMapper binInfoMapper = new BinInfoMapperImpl();
                binInfoList = binInfoMapper.selectAllCardBinInfoByBinNo(cardNo.substring(0, 2));
                if (null == binInfoList || binInfoList.isEmpty()) {
                    rglog.error("卡BIN配置信息不存在!");
                    return null;
                }
            }
        }
        for (BinInfo binInfo : binInfoList) {
            if (binInfo.getBinNo().trim().length() <= cardNo.trim().length()) {
                if (cardNo.startsWith(binInfo.getBinNo().trim()) && cardNo.trim().length() == binInfo.getCardNoLen()) {
                    return binInfo;
                }
            }
        }
        return null;
    }

    @Override
    public String getIssNameFromBinInfo(String issCode) throws Exception {
        if (null == issCode || issCode.trim().isEmpty()) {
            rglog.error("发卡行标识<{}>为空!", issCode);
            return null;
        }
        BinInfoMapper binInfoMapper = new BinInfoMapperImpl();
        List<BinInfo> binInfoList = binInfoMapper.selectAllCardBinInfoByIssuerCode(issCode);
        if (null == binInfoList || binInfoList.isEmpty()) {
            rglog.error("卡BIN配置信息不存在或发卡行标识<{}>为空!", issCode);
            return null;
        }
        for (BinInfo binInfo : binInfoList) {
            if (issCode.trim().equals(binInfo.getIssuerCode().trim())) {
                return binInfo.getIssuerName();
            }
        }
        return null;
    }
}
